﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.IO;
using System.Drawing;
using Newtonsoft.Json;

namespace iPublic.API
{
    /// <summary>
    /// 我们自己内部服务器的接口
    /// 修改记录：
    ///   20171214，zch，创建基本功能
    /// </summary>
    public partial class WoMen
    {
        //提示信息
        public iDefine.showInfoProc showInfoProc = null;


        #region //积分绑定用户通过用户名为用户增加积分
        public iDefine.ChuLiJieGuo 积分绑定用户通过用户名为用户增加积分(string sVipID)
        {
            iDefine.ChuLiJieGuo result = new iDefine.ChuLiJieGuo(), jg = null;
            string s = "", sUrl = "";
            try
            {
                //检查
                if (iDefine.toufangList == null || iDefine.toufangList.Count < 1) throw new Exception("物品箱是空的，请投放物品");

                //拼接、提交
                foreach (iDefine.json验证物品 itm in iDefine.toufangList) s += (s == "" ? "" : ",") + itm.result;
                sUrl = "http://h.sdzgwl.cn/api.php/user/addScoreByUserName?user_name=" + sVipID + "&id=" + s;
                jg = iPublicX.httpGet(sUrl, ref s);
                if (jg.error != 0) throw new Exception("积分绑定用户通过用户名为用户增加积分，出错：" + jg.error.ToString() + "," + jg.message);

                //分析服务器的返回值：{"result":true,"add_score":100}
                iDefine.json绑定用户增加积分 jf = JsonConvert.DeserializeObject<iDefine.json绑定用户增加积分>(s);
                if (jf == null || string.IsNullOrEmpty(jf.result) || jf.result.ToUpper() != "TRUE") throw new Exception("服务器判断微信会员积分出错了！返回值无效：" + s);

                //完成
                result.data = jf;
                result.error = 0;
                result.message = "ok";
            }
            catch (Exception x)
            {
                if (result.error <= 0) result.error = 100;
                result.message = x.Message;
            }
            return result;
        }
        #endregion


        #region //识别物品，返回服务器上的记录号，失败则返回0和msg
        /// <summary>
        /// 验证物品。文档网址：https://www.eolinker.com/#/home/project/inside/api/detail?groupID=-1&apiID=249219&projectName=%E5%9B%9E%E6%94%B6%E7%AE%B1%E5%AE%A4%E5%A4%96%E7%AB%AF%E6%8E%A5%E5%8F%A3&projectHashKey=TfjeHAnb1d5781111d84f7b3fe45a0852e59758cd7a87e5
        /// 传入阿里的识别结果id，返回是否接收
        /// 参考：
        ///   contentType类型：http://tool.oschina.net/commons
        /// </summary>
        /// <param name="shibie1"></param>
        /// <returns></returns>
        public iDefine.ChuLiJieGuo 验证物品(iDefine.jsonShibieOK shibie1, string sJpgImgFile)
        {
            iDefine.ChuLiJieGuo result = new iDefine.ChuLiJieGuo(), jg = null;
            //拼装get请求
            string s = "", sUrl = "http://h.sdzgwl.cn/api.php/user/insert_use";
            string goods_id = "", goods_name = "", contentType = "image/jpeg";
            //
            iHttpUpload http = null;
            FileStream fs = null;
            byte[] buf = null;
            try
            {
                foreach (iDefine.jsonShibieItem itm in shibie1.result)
                {
                    goods_id += (goods_id == "" ? "" : ",") + itm.id;
                    goods_name += (goods_name == "" ? "" : ",") + itm.description;
                }

                //sUrl = "http://h.sdzgwl.cn/api.php/user/insert_use?product_id=" + iDefine.SysConfig.machineID;
                //sUrl += "&goods_id=" + s;
                ////请求
                //jg = iPublicX.httpGet(sUrl, ref s);
                //if (jg.error != 0 || string.IsNullOrEmpty(s)) throw new Exception("请求出错：" + jg.error.ToString() + "," + jg.message);

                //20171215，识别改成用insert_offuse
                sUrl = "http://www.aigou198.com/api.php/user/insert_offuse";
                http = new iPublic.iHttpUpload();
                http.SetFieldValue("goods_id", goods_id);
                http.SetFieldValue("goods_name", goods_name);
                http.SetFieldValue("product_id", iDefine.SysConfig.machineID);
                if (!string.IsNullOrEmpty(sJpgImgFile))
                {
                    fs = File.OpenRead(sJpgImgFile);
                    buf = new byte[fs.Length];
                    fs.Read(buf, 0, buf.Length);
                    http.SetFieldValue("image", Path.GetFileName(sJpgImgFile), contentType, buf);
                }
                if (!http.Upload(sUrl, out s)) throw new Exception("POST提交出错！");    //提交

                //识别返回值
                iDefine.json验证物品 o = JsonConvert.DeserializeObject<iDefine.json验证物品>(s);
                if (o == null || string.IsNullOrEmpty(o.result) || o.result == "0") throw new Exception("物品识别返回值无效：" + s);
                if (string.IsNullOrEmpty(o.msg)) o.msg = "";

                //完成
                result.error = 0;
                result.data = o;
                result.message = "ok";
            }
            catch (Exception x)
            {
                result.error = 100;
                result.message = x.Message;
            }
            finally
            {
                if (fs != null) fs.Close();
                if (http != null) http = null;
            }
            return result;
        }
        #endregion


        public iDefine.ChuLiJieGuo 向服务器提交状态()
        {   //心跳包
            iDefine.ChuLiJieGuo result = new iPublic.iDefine.ChuLiJieGuo(), jg = null;
            iDefine.jsonBaiduGPS地址 gps = new iDefine.jsonBaiduGPS地址();
            string s = "", sUrl = "http://h.sdzgwl.cn/api.php/product/init", sMsg = "";
            try
            {
                //根据IP地址获取gps地址和城市
                showInfo("根据IP地址获取gps坐标和地址");
                if ((jg = iPublicX.getGPS地址()).error == 0)  //获取成功了
                    gps = jg.data as iDefine.jsonBaiduGPS地址;

                //准备：product_id=,status=,x=,y=,product_addr=
                sUrl += "?product_id=" + iDefine.SysConfig.machineID + "&status=" + iDefine.SysConfig.sStatus;
                sUrl += "&x=" + gps.content.point.x + "&y=" + gps.content.point.y + "&product_addr=" + gps.address;
                sMsg = gps.address + "," + gps.content.point.x + "," + gps.content.point.y;

                //通信
                showInfo("向服务器刷新状态");
                if ((jg = iPublicX.httpGet(sUrl, ref s)).error != 0)
                    throw new Exception("向服务器提交状态出错：" + jg.error.ToString() + "," + jg.message);

                //完成
                result.error = 0;
                result.message = "ok," + sMsg;
            }
            catch (Exception x)
            {
                if (result.error <= 0) result.error = 100;
                result.message = x.Message;
            }
            //完成
            return result;
        }

        public iDefine.ChuLiJieGuo 刷新广告设置()
        {
            iDefine.ChuLiJieGuo result = new iPublic.iDefine.ChuLiJieGuo(), jg = null;
            StreamWriter sw = null;
            StreamReader sr = null;
            string s = "", sUrl = "http://h.sdzgwl.cn/api.php/ad/get_ad", sFile = iDefine.findSysFile("App.Config");
            try
            {
                //准备
                sFile = Path.GetDirectoryName(sFile) + "\\Temp\\广告\\";
                if (!Directory.Exists(sFile)) Directory.CreateDirectory(sFile);
                sFile += "GuangGao.txt";

                //获取广告：http://h.sdzgwl.cn/api.php/ad/get_ad
                showInfo("读取广告设置");
                s = "";
                if ((jg = iPublicX.httpGet(sUrl, ref s)).error != 0)
                {   //读取出错，则尝试查找以前的老的
                    showInfo("读取设置：" + jg.error.ToString() + "," + jg.message + ",尝试查找上次的文件.");
                    if (File.Exists(sFile))
                    {
                        sr = File.OpenText(sFile);
                        s = sr.ReadToEnd();
                    }
                }
                else
                {   //记录到配置文件中
                    showInfo("保存广告设置到文件 " + sFile);
                    if (File.Exists(sFile)) File.Delete(sFile);
                    (sw = File.CreateText(sFile)).Write(s);
                }
                if (string.IsNullOrEmpty(s)) throw new Exception("从服务器读取广告失败，读取老文件也失败");

                //解析出来，下载新图片，删掉不要了的图片
                iDefine.guanggao = JsonConvert.DeserializeObject<iDefine.json广告清单>(s);
            }
            catch (Exception x)
            {
                if (result.error <= 0) result.error = 100;
                result.message = "刷新广告设置错误：" + x.Message;
            }
            finally
            {
                if (sw != null) sw.Close();     //释放文件
                if (sr != null) sr.Close();     //释放读取流
            }
            return result;
        }

        

        public void showInfo(string sInfo, bool lTime = true)
        {   //显示信息
            if (showInfoProc == null) return;
            showInfoProc(sInfo, lTime);
        }

    }

}
